﻿using Newtonsoft.Json;


namespace System
{
    public class LongToStringConverter : JsonConverter
    {
        private readonly Type Int64Type = typeof(long);

        private readonly Type Int64NullType = typeof(long?);
        public override bool CanConvert(Type objectType)
        {
            return objectType.Equals(Int64Type) || objectType.Equals(Int64NullType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (long.TryParse(reader.Value?.ToString(), out long value))
            {
                return value;
            }
            return existingValue;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null && (long)value < byte.MaxValue)
            {
                writer.WriteValue(value);
                return;
            }
            writer.WriteValue(value?.ToString());
        }
    }

}
